﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AlbumDesigner.Helpers;
using Keepo.Models;
using Keepo.Models.Services;
using AlbumDesigner.Models.Types;
using System.IO;

namespace AlbumDesigner.Controllers
{
    public class DesignVectorsController : Controller
    {
        private AlbumContext db = new AlbumContext();

        [CheckPermission(section = "DesignVectors")]
        public ActionResult Index()
        {
            return View();
        }

        [CheckPermission(section = "DesignVectors")]
        [HttpPost]
        public ActionResult GetDesignVectorsList(int categoryId, int Page = 1)
        {
            //get all the images of the specified Category
            var imagesList = db.DesignVectors.Where(m => m.VectorCategoryId == categoryId && m.IsRemoved == false).ToList();

            var images = imagesList.Select(m => new DesignVectorExport(m)).ToList();

            //add the Paging settings to the images list
            int rowsPerPage = 12;
            int imagesCount = images.Count();
            int startIndex = (Page - 1) * rowsPerPage;
            int pagesCount = imagesCount / rowsPerPage;
            if (imagesCount % rowsPerPage > 0)
            {
                pagesCount++;
            }

            var imagesPages = images.Skip(startIndex).Take(rowsPerPage);

            return Json(new { Images = imagesPages, Pages = pagesCount });
        }

        [CheckPermission(section = "DesignVectors")]
        public ActionResult GetCategoriesList()
        {
            //get all the categories
            var categoriesList = db.VectorCategories.ToList();

            var categories = categoriesList.Select(m => new ImageCategoryData(m)).ToList();

            return Json(categories);
        }

        [CheckPermission(section = "DesignVectors")]
        public ActionResult CategoryForm(int? id)
        {
            //edit mode
            if (id != null)
            {
                var category = db.VectorCategories.Find(id);
                return PartialView(category);
            }
            //insert mode
            else
            {
                return PartialView();
            }
        }

        [CheckPermission(section = "DesignVectors")]
        [HttpPost]
        public ActionResult AddCategory(VectorCategory category)
        {
            //insert this category
            db.VectorCategories.Add(category);
            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, "הקטגוריה נוספה בהצלחה."));
        }

        [CheckPermission(section = "DesignVectors")]
        [HttpPost]
        public ActionResult UpdateCategory(VectorCategory category)
        {
            //update this category
            var existingCategory = db.VectorCategories.Find(category.VectorCategoryId);
            existingCategory.Title = category.Title;
            existingCategory.TitleHebrew = category.TitleHebrew;

            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, "הקטגוריה עודכנה בהצלחה."));
        }

        [CheckPermission(section = "DesignVectors")]
        public ActionResult DeleteCategory(int id)
        {
            //find this category
            var category = new ImageCategoryData(db.VectorCategories.Find(id));

            //get all the categories as SelectList
            ViewBag.MoveToCategoryId = new SelectList(db.VectorCategories.Where(m => m.VectorCategoryId != id), "VectorCategoryId", "TitleHebrew");

            return PartialView(category);
        }

        [CheckPermission(section = "DesignVectors")]
        [HttpPost]
        public ActionResult DeleteCategory(int categoryId, int? moveToCategoryId)
        {
            //find this category
            var category = db.VectorCategories.Find(categoryId);

            //get all images of category
            var categoryImages = db.DesignVectors.Where(m => m.VectorCategoryId == categoryId).ToList();

            var message = "הקטגוריה " + category.TitleHebrew + " נמחקה בהצלחה.";

            if (moveToCategoryId == null)
            {
                //delete all the vectors of this category
                if (categoryImages.Count > 0)
                {
                    categoryImages.ForEach(m => db.DesignVectors.Remove(m));
                    db.SaveChanges();
                }
            }
            else
            {
                //move all image of category to a different specified category
                categoryImages.ForEach(m => m.VectorCategoryId = moveToCategoryId.Value);
                db.SaveChanges();

                message = "הקטגוריה " + category.TitleHebrew + " נמחקה והתמונות שבה הועברו לקטגוריה הנבחרת.";
            }

            //delete the category
            db.VectorCategories.Remove(category);
            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, message));
        }

        [CheckPermission(section = "DesignVectors")]
        public ActionResult AddDesignVector(int categoryId)
        {
            //get all the categories as SelectList
            ViewBag.CategoryId = new SelectList(db.VectorCategories, "VectorCategoryId", "TitleHebrew", categoryId);

            return PartialView();
        }

        [CheckPermission(section = "DesignVectors")]
        [HttpPost]
        public ActionResult AddDesignVector(DesignVectorExport image)
        {
            //add the design vector to the DB
            var designVector = new DesignVector();
            designVector.Title = image.Title;
            designVector.URL = image.ThumbnailUrl;
            designVector.VectorCategoryId = image.VectorCategoryId;

            if (!string.IsNullOrEmpty(designVector.URL))
            {
                db.DesignVectors.Add(designVector);
                db.SaveChanges();
            }

            return Json(new KeyValuePair<bool, string>(true, "המדבקה נוספה בהצלחה."));
        }

        [CheckPermission(section = "DesignVectors")]
        [HttpPost]
        public ActionResult UploadImage(HttpPostedFileBase file)
        {
            if (file != null)
            {
                //generate file name for this image (guid string)
                var fileName = Guid.NewGuid().ToString().Substring(0, 6) + Path.GetExtension(file.FileName);

                //upload the image to the resources directory
                var directoryToSave = Server.MapPath("~/resources/vectors/" + fileName);
                file.SaveAs(directoryToSave);

                return Content("resources/vectors/" + fileName);
            }
            return Content("");
        }

        [CheckPermission(section = "DesignVectors")]
        public ActionResult UpdateDesignVector(int id)
        {
            var designVector = new DesignVectorExport(db.DesignVectors.Find(id));

            return PartialView(designVector);
        }

        [CheckPermission(section = "DesignVectors")]
        [HttpPost]
        public ActionResult UpdateDesignVector(DesignVectorExport image)
        {
            //find the specified image and update its details
            var existImage = db.DesignVectors.Find(image.DesignVectorId);

            existImage.Title = image.Title;

            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, "המדבקה עודכנה בהצלחה."));
        }

        [CheckPermission(section = "DesignVectors")]
        [HttpPost]
        public ActionResult MoveImagesToCategory(string imagesIds, int categoryId)
        {
            var images = imagesIds.Split(',');

            //loop through all the specified images
            foreach (var imageId in images)
            {
                if (!string.IsNullOrEmpty(imageId))
                {
                    //find the DesignVector and update its Category
                    var designVector = db.DesignVectors.Find(int.Parse(imageId));
                    designVector.VectorCategoryId = categoryId;

                }
            }

            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, "המדבקה הועברה בהצלחה."));
        }

        [CheckPermission(section = "DesignVectors")]
        [HttpPost]
        public ActionResult DeleteDesignVector(string imagesIds)
        {
            var images = imagesIds.Split(',');

            //loop through all the specified images
            foreach (var imageId in images)
            {
                if (!string.IsNullOrEmpty(imageId))
                {
                    //find the DesignVector and delete it
                    var designVector = db.DesignVectors.Find(int.Parse(imageId));
                    designVector.IsRemoved = true;
                    db.SaveChanges();
                }
            }

            return Json(new KeyValuePair<bool, string>(true, "המדבקה נמחקה בהצלחה."));
        }

        [CheckPermission(section = "DesignVectors")]
        public ActionResult UploadMultiple(int categoryId)
        {
            //get all the categories as SelectList
            ViewBag.CategoryId = new SelectList(db.VectorCategories, "VectorCategoryId", "TitleHebrew", categoryId);

            return View();
        }

        [CheckPermission(section = "DesignVectors")]
        [HttpPost]
        public ActionResult UploadMultiple(string Title, int CategoryId, int FileIndex, int chunk = 0, int chunks = 1)
        {
            //check if there is a file uploaded
            if (Request.Files[0] != null)
            {
                HttpPostedFileBase Filedata = (Request.Files[0] as HttpPostedFileBase);

                //add the vector to the DB
                var vector = new DesignVector();
                if (!string.IsNullOrEmpty(Title))
                {
                    vector.Title = Title + " - " + FileIndex;
                }
                vector.VectorCategoryId = CategoryId;

                //find the relevant Directory that these files will be saved into
                var directoryToSave = Server.MapPath("~/resources/vectors");
                var url = "resources/vectors";

                if (chunk == 0)
                {
                    //generate file name for this image (guid string)
                    Session["FileName"] = Guid.NewGuid().ToString().Substring(0, 6) + Path.GetExtension(Filedata.FileName);
                }

                //save the file (the file could be sent in chunks, if it's big)
                using (var fs = new FileStream(directoryToSave + "\\" + Session["FileName"], chunk == 0 ? FileMode.Create : FileMode.Append))
                {
                    var buffer = new byte[Filedata.InputStream.Length];
                    Filedata.InputStream.Read(buffer, 0, buffer.Length);

                    fs.Write(buffer, 0, buffer.Length);
                }

                vector.URL = url + "/" + Session["FileName"];

                //if this is the last chunk of the file
                if (chunk == chunks - 1)
                {
                    db.DesignVectors.Add(vector);
                    db.SaveChanges();
                    Session["FileName"] = "";
                }
            }

            return Json(true);
        }

        public ActionResult Seed()
        {
            using (var context = new AlbumContext())
            {
                var vectorCatetories = new List<VectorCategory>()
                {
                    new VectorCategory { Title = "Office", TitleHebrew = "משרד" },
                    new VectorCategory { Title = "Celebration", TitleHebrew = "חגיגה" }
                };

                vectorCatetories.ForEach(s => context.VectorCategories.AddOrUpdate(t => t.Title, s));
                context.SaveChanges();

                ImportSwfFromDirectory(context, "Office", @"resources\vectors\clips\");
                ImportSwfFromDirectory(context, "Celebration", @"resources\vectors\celebration\");

                return Json(true, JsonRequestBehavior.AllowGet);
            }
        }

        private void ImportSwfFromDirectory(AlbumContext context, string categoryTitle, string dir)
        {
            var directory = Server.MapPath(@"~\" + dir);

            // find corresponding category id
            var category = context.VectorCategories.Where(m => m.Title == categoryTitle).FirstOrDefault();

            if (category == null)
            {
                return;
            }

            if (Directory.Exists(directory))
            {
                var files = Directory.GetFiles(directory, "*.swf");
                foreach (var file in files)
                {
                    var vector = new DesignVector();
                    vector.VectorCategoryId = category.VectorCategoryId;

                    var swfFilename = dir + System.IO.Path.GetFileName(file);

                    vector.URL = swfFilename;
                    context.DesignVectors.AddOrUpdate(t => t.URL, vector);
                }
            }

            context.SaveChanges();
        }
    }
}
